package com.kly.pay.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
import com.google.api.services.androidpublisher.model.*;
import com.kly.enums.*;
import com.kly.pay.db.dao.POrderDao;
import com.kly.pay.db.dao.POrderRepayDao;
import com.kly.pay.db.entity.POrderEntity;
import com.kly.pay.db.entity.POrderRepayEntity;
import com.kly.pay.factory.GoogleApiService;
import com.kly.pay.factory.PayServiceFactory;
import com.kly.pay.service.BasicPayActionService;
import com.kly.pay.service.RetryTaskService;
import com.kly.req.RepayRequest;
import com.kly.req.RepayStatusRequest;
import com.kly.rsp.RepayResponse;
import com.kly.rsp.RepayStatusResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * googlePay支付处理类（处理订阅类商品支付）
 * @author linqu
 */
@Service
@Slf4j
public class GoogleSubScriptionsBasicPayImpl implements BasicPayActionService {

    @Resource
    POrderDao pOrderDao;
    @Resource
    POrderRepayDao pOrderRepayDao;
    @Resource
    PayServiceFactory payServiceFactory;
    @Resource
    RetryTaskService retryTaskService;

    /**
     * 返回支付网关：googlePay
     */
    @Override
    public PayGatewayEnum getPayType() {
        return PayGatewayEnum.GOOGLE_PAY_SUBSCRIPTIONS;
    }

    private GoogleApiService getGoogleApiService(String packageName) {
        return payServiceFactory.buildGooglePayChannel(packageName);
    }

    /**
     * googlepay 调用到此接口时，已经通过SDK下单成功，需要调用消耗api(其实相当于二次确认），资金才会真正入账
     */
    @Override
    public RepayResponse repay(String payOrderNo, RepayRequest repayRequest) {
        log.info("[PaymentLog-subscriptions-repay] repay begin, userCode:{} orderNo:{} repayRequest:{}", repayRequest.getUserCode(), repayRequest.getOrderNo(), JSONObject.toJSONString(repayRequest));

        final String payExt = Optional.ofNullable(repayRequest.getPayExt()).orElse("");
        final JSONObject payExtJson = JSONObject.parseObject(payExt);

        AndroidPublisher.Purchases.Subscriptionsv2 subscriptionsv2
                = getGoogleApiService(payExtJson.getString("packageName")).getSubscriptionsv2();

        try {

            SubscriptionPurchaseV2 purchase = getSubscriptionPurchaseV2(payOrderNo, repayRequest.getUserCode(), repayRequest.getOrderNo(), subscriptionsv2, payExtJson.getString("packageName"), payExtJson.getString("purchaseToken"));

            final POrderEntity payOrder = pOrderDao.queryByPayOrderNo(payOrderNo);
            if (Objects.isNull(payOrder)) {
                log.error("[PaymentLog-subscriptions-repay] ThePayOrderNotExists, userCode:{}, orderNo:{} payOrderNo:{}", repayRequest.getUserCode(), repayRequest.getOrderNo(), payOrderNo);
                throw new ApplicationException("ThePayOrderNotExists, payOrderNo:" + payOrderNo);
            }
            if (OrderStatus.PAID.getStatus() == payOrder.getStatus() || OrderStatus.CLOSE.getStatus() == payOrder.getStatus()) {
                log.info("[PaymentLog-subscriptions-repay] orderHasPaidOrClosed, userCode:{}, orderNo:{}, payOrderNo:{}", repayRequest.getUserCode(), repayRequest.getOrderNo(), payOrderNo);
                return RepayResponse.builder().payStatusEnum(PayStatusEnum.getEnumByCode(String.valueOf(payOrder.getStatus())))
                        .orderNo(payOrder.getOrderNo()).payOrderNo(payOrderNo).build();
            }

            // 订阅处于有效状态。
            //
            PayStatusEnum payStatusEnum = PayStatusEnum.PROCESSING;
            final String acknowledgementState = purchase.getAcknowledgementState();

            if (AcknowledgementState.ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED.name().equalsIgnoreCase(acknowledgementState)) {
                // 修改订单受理状态
                payStatusEnum = PayStatusEnum.PAY_SUCCESS;
                pOrderDao.repaySuccess(payOrderNo, payOrder.getPayType());
                // 插入入账成功记录表
                addRepayment(payOrderNo, payOrder);
                log.info("[PaymentLog-subscriptions-repay] orderHasPaidSuccess, userCode:{}, orderNo:{}", repayRequest.getUserCode(), repayRequest.getOrderNo());
                return RepayResponse.builder().payOrderNo(payOrderNo).payStatusEnum(payStatusEnum).build();
            }

            // 其它当作处理中处理（消耗后等待支付回调处理）
            if (AcknowledgementState.ACKNOWLEDGEMENT_STATE_PENDING.name().equalsIgnoreCase(acknowledgementState)
                    || AcknowledgementState.ACKNOWLEDGEMENT_STATE_UNSPECIFIED.name().equalsIgnoreCase(acknowledgementState)) {
                acknowledge(repayRequest.getUserCode(), repayRequest.getOrderNo(), payExtJson.getString("packageName"), payExtJson.getString("productId")
                        , payExtJson.getString("purchaseToken"), payExtJson.getString("orderId"));
                pOrderDao.updateOrderStatus(payOrderNo, PayTypeEnum.REPAY.getCode(), payStatusEnum.getCode());
                log.info("[PaymentLog-subscriptions-repay] orderHasPaidSuccess, userCode:{}, orderNo:{}", repayRequest.getUserCode(), repayRequest.getOrderNo());

                // 增加重试任务
                retryTaskService.addTask(payOrderNo);
                return RepayResponse.builder().payOrderNo(payOrderNo).payStatusEnum(payStatusEnum).build();
            }

            log.info("==========>订单校验【失败】, payOrderNo:{}", payOrderNo);
        } catch (Exception e) {
            log.info("==========>订单校验【失败】, payOrderNo:{}", payOrderNo, e);
        }

        return null;
    }

    @Override
    public RepayStatusResponse repayStatusQuery(RepayStatusRequest repayStatusRequest) {


        final String payOrderNo = repayStatusRequest.getPayOrderNo();
        final String repayStatusExtReq = repayStatusRequest.getRepayStatusExtReq();
        final JSONObject repayStatusExtJson = JSONObject.parseObject(repayStatusExtReq);
        final String packageName = repayStatusExtJson.getString("packageName");
        final String productId = repayStatusExtJson.getString("productId");
        final String purchaseToken = repayStatusExtJson.getString("purchaseToken");
        final String orderId = repayStatusExtJson.getString("orderId");

        final POrderEntity payOrder = pOrderDao.queryByPayOrderNo(payOrderNo);
        if (Objects.isNull(payOrder)) {
            log.error("[PaymentLog-subscriptions-repayStatusQuery] ThePayOrderNotExists, userCode:{} orderNo:{} payOrderNo:{}", repayStatusRequest.getUserCode(), repayStatusRequest.getOrderNo(), payOrderNo);
            return null;
        }

        if (OrderStatus.PAID.getStatus() == payOrder.getStatus() || OrderStatus.CLOSE.getStatus() == payOrder.getStatus()) {
            log.info("[PaymentLog-subscriptions-repayStatusQuery] orderHasPaidOrClosed, userCode:{}, payOrderNo:{}, payOrderNo:{}", repayStatusRequest.getUserCode(), repayStatusRequest.getOrderNo(), payOrderNo);
            return RepayStatusResponse.builder().status(PayStatusEnum.getEnumByCode(String.valueOf(payOrder.getStatus())))
                    .orderNo(payOrder.getOrderNo()).payOrderNo(payOrderNo).build();
        }

        // 获取订阅订单信息
        SubscriptionPurchaseV2 purchase = getSubscriptionPurchaseV2(payOrderNo, repayStatusRequest.getUserCode(), repayStatusRequest.getOrderNo(),
                getGoogleApiService(packageName).getSubscriptionsv2(), packageName, purchaseToken);
        PayStatusEnum payStatusEnum = PayStatusEnum.PROCESSING;
        // 订阅是否付款标志
        final String acknowledgementState = purchase.getAcknowledgementState();

        if (AcknowledgementState.ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED.name().equalsIgnoreCase(acknowledgementState)) {
            // 修改订单受理状态
            payStatusEnum = PayStatusEnum.PAY_SUCCESS;
            pOrderDao.repaySuccess(payOrderNo, payOrder.getPayType());
            // 插入入账成功记录表
            addRepayment(payOrderNo, payOrder);
            log.info("[PaymentLog-subscriptions-repayStatusQuery] orderHasPaidSuccess, userCode:{}, orderNo:{}, payOrderNo:{}", repayStatusRequest.getUserCode(), repayStatusRequest.getOrderNo(), payOrderNo);
            return RepayStatusResponse.builder().payOrderNo(payOrderNo).status(payStatusEnum).startTime(purchase.getStartTime()).expiryTime(getMaxExpiryTime(purchase)).purchaseResult(JSONObject.toJSONString(purchase)).build();
        }

        // 其它当作处理中处理
        if (AcknowledgementState.ACKNOWLEDGEMENT_STATE_PENDING.name().equalsIgnoreCase(acknowledgementState)
                || AcknowledgementState.ACKNOWLEDGEMENT_STATE_UNSPECIFIED.name().equalsIgnoreCase(acknowledgementState)) {
            acknowledge(repayStatusRequest.getUserCode(), repayStatusRequest.getOrderNo(), packageName, productId, purchaseToken, orderId);
            pOrderDao.updateOrderStatus(payOrderNo, PayTypeEnum.REPAY.getCode(), payStatusEnum.getCode());
            log.info("[PaymentLog-onTimePurchase-repayStatusQuery] orderHasAcknowledgeSuccess, userCode:{}, orderNo:{} repayRequest:{}", repayStatusRequest.getUserCode(), repayStatusRequest.getOrderNo(), payOrderNo);
            return RepayStatusResponse.builder().payOrderNo(payOrderNo).status(payStatusEnum).build();
        }

        final String purchaseState = purchase.getSubscriptionState();

        /**
         * google pay 订阅状态
         * SUBSCRIPTION_STATE_UNSPECIFIED	未指定订阅状态。
         * SUBSCRIPTION_STATE_PENDING	已创建订阅，但在注册期间正在等待付款。在此状态下，所有商品均正在等待付款。
         * SUBSCRIPTION_STATE_ACTIVE	订阅处于有效状态。- (1) 如果订阅是自动续订型方案，则至少有一项是自动续订状态并且未过期。- (2) 如果订阅是预付费方案，至少有一项不会过期。
         * SUBSCRIPTION_STATE_PAUSED	订阅已暂停。只有在订阅是自动续订型方案时，才会显示该状态。在此状态下，所有商品均处于暂停状态。
         * SUBSCRIPTION_STATE_IN_GRACE_PERIOD	订阅处于宽限期。只有在订阅是自动续订型方案时，才会显示该状态。在此状态下，所有商品均处于宽限期。
         * SUBSCRIPTION_STATE_ON_HOLD	订阅已暂停（已暂停）。只有在订阅是自动续订型方案时，才会显示该状态。在此状态下，所有商品均处于保全状态。
         * SUBSCRIPTION_STATE_CANCELED	订阅已取消，但尚未过期。只有在订阅是自动续订型方案时，才会显示该状态。所有商品的 autoRenewEnabled 都设为 false。
         * SUBSCRIPTION_STATE_EXPIRED	订阅已过期。所有内容的过期时间都是过去的时间。
         * @author linqu
         */

        // 订阅已过期。所有内容的过期时间都是过去的时间。
        if (GooglePaySubscriptionsStatus.SUBSCRIPTION_STATE_EXPIRED.name().equalsIgnoreCase(purchaseState)
                // 订阅已取消，但尚未过期（当前已买的依然有效，可以在有效期内继续使用）
                || GooglePaySubscriptionsStatus.SUBSCRIPTION_STATE_CANCELED.name().equalsIgnoreCase(purchaseState)
                // 订阅已暂停（已暂停，当作付费不成功处理）
                || GooglePaySubscriptionsStatus.SUBSCRIPTION_STATE_ON_HOLD.name().equalsIgnoreCase(purchaseState)
                // 订阅处于宽限期（内部订单当作付费不成功处理）
                || GooglePaySubscriptionsStatus.SUBSCRIPTION_STATE_IN_GRACE_PERIOD.name().equalsIgnoreCase(purchaseState)) {
            payStatusEnum = PayStatusEnum.CLOSED_ORDER;
            pOrderDao.updateOrderStatus(payOrderNo, PayTypeEnum.REPAY.getCode(), payStatusEnum.getCode());
            return RepayStatusResponse.builder().payOrderNo(payOrderNo).status(payStatusEnum).build();
        }

        return null;
    }

    private String getMaxExpiryTime(SubscriptionPurchaseV2 purchase) {
        final List<SubscriptionPurchaseLineItem> lineItems = purchase.getLineItems();
        String expiryTime = null;
        if (CollectionUtils.isNotEmpty(lineItems)) {
            expiryTime = lineItems.parallelStream().filter(o -> StringUtils.isNotEmpty(o.getExpiryTime())).map(o -> DateUtil.parseUTC(o.getExpiryTime())).max(Date::compareTo).map(dd -> DateUtil.format(dd, "yyyy-MM-dd HH:mm:ss")).orElse(null);
        }
        return expiryTime;
    }

    /**
     * 商品消耗
     */
    public void acknowledge(String userCode, String orderNo, String packageName ,String productId, String purchaseToken, String orderId) {
        try{

            SubscriptionPurchasesAcknowledgeRequest content = new SubscriptionPurchasesAcknowledgeRequest();
            content.put("orderId", orderId);
            final AndroidPublisher.Purchases.Subscriptions.Acknowledge acknowledge
                    = getGoogleApiService(packageName).getSubscriptions().acknowledge(packageName, productId, purchaseToken, content);
            acknowledge.execute();
            log.info("[PaymentLog-subscriptions-repay] AndroidPublisher.Purchases.Subscriptions.acknowledge success, userCode:{}, orderNo:{}, packageName:{}, productId:{}, purchaseToken:{}", userCode, orderNo, packageName, productId, purchaseToken);
        } catch (Exception ex) {
            log.error("[PaymentLog-subscriptions-repay] AndroidPublisher.Purchases.Subscriptions.acknowledge failed, userCode:{}, orderNo:{}, packageName:{}, productId:{}, purchaseToken:{}", userCode, orderNo, packageName, productId, purchaseToken, ex);
            throw new ApplicationException("AndroidPublisher.Purchases.Subscriptions.acknowledge failed");
        }
    }

    /**
     * 调用googlePay api获取订单状态
     * packageName: 引号内包名
     * productId: 产品ID
     * purchaseToken: 访问googlePay的purchaseToken
     */
    private static SubscriptionPurchase getSubscriptionPurchase(String payOrderNo, String userCode, String orderNo,
            AndroidPublisher.Purchases.Subscriptions subscriptions, String packageName, String productId, String purchaseToken) {

        try {
            AndroidPublisher.Purchases.Subscriptions.Get sub = subscriptions.get(
                    packageName,
                    productId, purchaseToken);
            final SubscriptionPurchase subscriptionPurchase = sub.execute();
            log.info("[PaymentLog-subscriptions-repay] GetSubscriptionPurchase, payOrderNo:{}, userCode:{}, orderNo:{} productPurchaseResult:{}", payOrderNo,  userCode, orderNo, JSONObject.toJSONString(subscriptionPurchase));
            return subscriptionPurchase;
        } catch (Exception e) {
            log.error("AndroidPublisher.Purchases.Subscriptions.Get.execute failed, packageName:{}, productId:{}, purchaseToken:{}", packageName, productId, purchaseToken, e);
            throw new ApplicationException("AndroidPublisher.Purchases.Subscriptions.Get.execute failed");
        }
    }

    /**
     * 调用googlePay api获取订单状态
     * packageName: 引号内包名
     * productId: 产品ID
     * purchaseToken: 访问googlePay的purchaseToken
     */
    private static SubscriptionPurchaseV2 getSubscriptionPurchaseV2(String payOrderNo, String userCode, String orderNo,
            AndroidPublisher.Purchases.Subscriptionsv2 subscriptions, String packageName,  String purchaseToken) {

        try {
            AndroidPublisher.Purchases.Subscriptionsv2.Get sub = subscriptions.get(
                    packageName, purchaseToken);
            final SubscriptionPurchaseV2 subscriptionPurchaseV2 = sub.execute();
            log.info("[PaymentLog-subscriptions-repay] getSubscriptionPurchaseV2, payOrderNo:{}, userCode:{}, orderNo:{} productPurchaseResult:{}", payOrderNo,  userCode, orderNo, JSONObject.toJSONString(subscriptionPurchaseV2));
            return subscriptionPurchaseV2;
        } catch (Exception e) {
            log.error("AndroidPublisher.Purchases.SubscriptionsV2.Get.execute failed, packageName:{}, purchaseToken:{}", packageName, purchaseToken, e);
            throw new ApplicationException("AndroidPublisher.Purchases.SubscriptionsV2.Get.execute failed");
        }
    }

    /**
     * 添加入账记录
     */
    private void addRepayment(String payOrderNo, POrderEntity payOrder) {
        final POrderRepayEntity repayOrder = pOrderRepayDao.queryByPayOrderNo(payOrderNo);
        if (Objects.nonNull(repayOrder)) {
            return;
        }
        POrderRepayEntity entity = new POrderRepayEntity();
        entity.setAmount(payOrder.getAmount());
        entity.setCreatedBy("admin");
//                entity.setMerchantCode()
        entity.setOrderNo(payOrder.getOrderNo());
        entity.setPayGateway(payOrder.getPayGateway());
        entity.setPayOrderNo(payOrderNo);
        entity.setProductCode(payOrder.getProductCode());
        entity.setRepayAccount(payOrder.getUserCode());
        pOrderRepayDao.insert(entity);
    }




    /**
     * 获取用户订阅
     */
    @Override
    public String queryExtentInfo(RepayRequest repayRequest) {
        final String payExt = Optional.ofNullable(repayRequest.getPayExt()).orElse("");
        final JSONObject payExtJson = JSONObject.parseObject(payExt);
        try {
            final SubscriptionPurchaseV2 subscriptionPurchaseV2 = getSubscriptionPurchaseV2("", "", "",
                    getGoogleApiService(payExtJson.getString("packageName")).getSubscriptionsv2(), payExtJson.getString("packageName"), payExtJson.getString("purchaseToken"));
            if (Objects.isNull(subscriptionPurchaseV2)) {
                return null;
            }
            final String result = JSONObject.toJSONString(subscriptionPurchaseV2);
            log.info("[PaymentLog-subscriptions-queryExtentInfo] repayRequest:{}, result:{}", JSONObject.toJSONString(repayRequest), result);
            return result;
        } catch (Exception e) {
            log.error("[PaymentLog-subscriptions-queryExtentInfo] QueryExtentInfoFailed, params:{}", JSONObject.toJSONString(repayRequest), e);
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String googlePayCredential = "{\n" +
                "  \"type\": \"service_account\",\n" +
                "  \"project_id\": \"pc-api-7210134977335577673-546\",\n" +
                "  \"private_key_id\": \"b4b3af0e9dcc19259aac154c45dd24ac14f8df14\",\n" +
                "  \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDOrqt4tlgV/vZO\\noaXf8BAjgtHOuJksZw8VPNAnnJAuSEy+3gDkKqvJZ1DgjBbvk7yz29BWXEYNBHkD\\npuMW48Q7UgwAMFQYPxXdk+YOPwrM2FtsUGD/5WvY1cvX/EIw8ys25AladqAqH+7D\\nH/HoTMx03B1Mqbo74pqvgZFfPy3GAlZkjd5t7e4z+HQvs9DWU+S4ezKgX9rrJjo6\\nb3jHoQhVtg5ZDB2QTizCwp4cP8ILgg7P7YjrQPHCE6Ays645nr5dwwLG3hqNxJf2\\nlIi3DlB5YhIiUw2cl2x9XMjcpLgd9sbnLWXIfI7/boHkjEIdv314ffyWXQKz0pUE\\npwvEhtybAgMBAAECggEAMnxPLVrZNHJFpxpsQsHIp2v2pPjJjaOU9xqWO/7N50hI\\n2tyuug1EThubEWaW2amsUADTKK08fUSI7N/wm7BCSD036jnj6NJMHIZajUNP946n\\n8lLGBuv7Bone06DuaDeV6EAWms7cO732HBqrBBPyY187FvVkpOkq4NEU+f+cRj/u\\nWPn6N0xNv7O5wxU4w+32Eqh5RBluwsiepsv4YTISOj+8kZYCoNyNuQim1K5S94QX\\nX4qJZJrnOQpq48GTJWCEAvpZLsA/qd4/aamnw4ejJs7vo1JsJALtbSA6/PnAj+Q6\\nGRG1GL+BkKLU+Cw7AC7AnLZGVXKO2Pz4x9V0pHkpyQKBgQD0CfNLpU5NRMxsdqYm\\n7TFGGdAWwpEEcvM2g0wfLVKql+U8N0kWyW4U8PiOl5R0StT6t3gd6BmYrQlTyh2n\\n3FlTuaD6ncWNhcr9PVuBfscWZdIAymIIG4BWKpLNr2pIdQYgxsMF9HxYV960dL0J\\nrTao5CDKYof5h/Y5nZ26f9CGSQKBgQDYz/4Dcop8tJZn/qomqHIrV9dd1pWpkeZH\\nwrS75FLWR8JNr2GeaQzgO0uWAmyCvjhwMEFmEZTQBRguIkOTAJ0hul0Fn9Fj2/Ge\\nwTvBhJVRh2E8y9rdqZh3q7sx9+BzjTK52vvITSSQrzcespATQr8sPM/3Ze1i2+Pg\\ncmkbYM/7wwKBgQDpU2ou9Uo8Tn81ZOvPZBEseRmf6T9GBbHMeRSa6naTbM9cF2/m\\nPYjmtM6xZvQljDa90BUkYvm2JBs65ZAdImy1xFHJzHdJrJY8MiH/Wft3yrpSzy2T\\nmtfFisb5qbHwvRKy29czJmKNBNaFqufjDJ2qNRO07SgcyIX+6FgaLIJvIQKBgDgf\\n12yDCRBxGwI+rUMmla9cpNaYxtNHfmoTIAAHgd4QY18CyG1eWkPtdYqWhApwPWHl\\nS/ilEnWq6/B9VCrInORvPsdG8Mg91lU3RkW5EYIyXlyDlNuOnHZWETZFKWggJAJy\\ninz2Y0HE6arbpGon/B7yew9a5lGSBHJEi6rXq99LAoGBANvqZL0mwHlpg1DrJnl5\\nBQxyRPHhhJ1r9nOpB2tDO7XUTFVY/GLq+4IXh+THjzc4Nr+8j9KEazIcvuIKIWTr\\nZI1WLlFTYaPQAg2gTRGg8RJmVQ87fVHWVxMW9p3/nnEqk7Jdnf7jMGlAH5wAheq7\\npchxTSFCLkDInyonOkgF3GMj\\n-----END PRIVATE KEY-----\\n\",\n" +
                "  \"client_email\": \"meboo-pay@pc-api-7210134977335577673-546.iam.gserviceaccount.com\",\n" +
                "  \"client_id\": \"109096292774436145524\",\n" +
                "  \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n" +
                "  \"token_uri\": \"https://oauth2.googleapis.com/token\",\n" +
                "  \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n" +
                "  \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/meboo-pay%40pc-api-7210134977335577673-546.iam.gserviceaccount.com\",\n" +
                "  \"universe_domain\": \"googleapis.com\"\n" +
                "}";
        GoogleCredential credential = GoogleCredential.fromStream(new ByteArrayInputStream(googlePayCredential.getBytes()))
                .createScoped(AndroidPublisherScopes.all());
        //credential.refreshToken();//注意这里
        if(credential==null) {
            log.error("==========>Get GoogleCredential fails 获取谷歌凭证失败！");
        }
        String packageName = "com.kly.meboo";
        String productId = "meboo_subscription_101";
        String token = "edmeghompoglaleocchijibh.AO-J1OwqyzzAGrtqZ9AFzNzWH8hPKfBubwLt5CS9l1rcDou5ZaUJ7vVi1VsJCv2J0vDa4_0UjHwiqdDKYSIS1vBnNhQALkVLpQ";

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JacksonFactory jacksonFactory = JacksonFactory.getDefaultInstance();
        AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jacksonFactory, credential).build();
        final AndroidPublisher.Purchases.Subscriptions subscriptions = publisher.purchases().subscriptions();
        final AndroidPublisher.Purchases.Subscriptionsv2 subscriptionsv2 = publisher.purchases().subscriptionsv2();
        SubscriptionPurchaseV2 subscriptionPurchaseV2 = getSubscriptionPurchaseV2("", "", "", subscriptionsv2, packageName, token);
        System.out.println("subscriptionPurchaseV2:" + JSONObject.toJSONString(subscriptionPurchaseV2));
        final SubscriptionPurchase meboo_subscription_101 = getSubscriptionPurchase("", "", "", subscriptions, packageName, productId,  token);
        System.out.println("subscriptionPurchase:" + JSONObject.toJSONString(meboo_subscription_101));


        SubscriptionPurchasesAcknowledgeRequest content = new SubscriptionPurchasesAcknowledgeRequest();
        content.put("orderId", "orderId-123");
        final AndroidPublisher.Purchases.Subscriptions.Acknowledge acknowledge
                = subscriptions.acknowledge(packageName, productId, token, content);
        acknowledge.execute();


        subscriptionPurchaseV2 = getSubscriptionPurchaseV2("", "", "", subscriptionsv2, packageName, token);
        System.out.println("subscriptionPurchaseV2:" + JSONObject.toJSONString(subscriptionPurchaseV2));



    }
}
